import router from '@/router'
import { getToken } from '@/utils/token-utils'
import { useUserInfoStore } from '@/stores/userInfo'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import getPageTitle from "@/utils/get-page-title"

const whiteList = ['/login', '/404']
router.beforeEach(async (to, from, next) => {
  document.title = getPageTitle(to.meta.title as string)
  NProgress.start()
  const token = getToken()
  if (token) {
    if (to.path === '/login') {
      next('/home')
      NProgress.done()
    } else {
      const userInfoStore = useUserInfoStore()
      if (userInfoStore.userInfo.name) {
        next()
        NProgress.done()
      } else {
        try {
          await userInfoStore.getInfo()
          next(to)
          NProgress.done()
        } catch (error) {
          await userInfoStore.reset()
          next('/login')
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

router.afterEach((to, from) => {
  NProgress.done()
})
